{% extends "base.html" %}

{% block title %}数据分析仪表板{% endblock %}

{% block head %}
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js"></script>
<style>
.chart-container {
    height: 300px;
    margin-bottom: 20px;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <h2 class="mb-4"><i class="fas fa-chart-line me-2"></i>数据分析仪表板</h2>
    
    <div class="mb-3">
        <a href="{{ url_for('analytics.advanced') }}" class="btn btn-outline-primary me-2">
            <i class="fas fa-chart-pie me-1"></i> 查看高级分析
        </a>
        <a href="{{ url_for('analytics.user_behavior_dashboard') }}" class="btn btn-outline-success">
            <i class="fas fa-user-chart me-1"></i> 查看用户行为分析
        </a>
    </div>
    
    <div class="row">
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">近30天销售趋势</h5>
                </div>
                <div class="card-body">
                    <div id="sales-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">用户行为分布</h5>
                </div>
                <div class="card-body">
                    <div id="behavior-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row mt-4">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">热门盲盒排行</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>排名</th>
                                    <th>盲盒</th>
                                    <th>销售额</th>
                                    <th>订单数</th>
                                </tr>
                            </thead>
                            <tbody id="popular-boxes">
                                <tr>
                                    <td colspan="4" class="text-center">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 初始化图表
const salesChart = echarts.init(document.getElementById('sales-chart'));
const behaviorChart = echarts.init(document.getElementById('behavior-chart'));

// 加载销售数据
fetch('/analytics/api/sales_summary')
    .then(response => response.json())
    .then(data => {
        const dates = data.map(item => item.date);
        const amounts = data.map(item => item.amount);
        const counts = data.map(item => item.count);
        
        salesChart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['销售额', '订单数']
            },
            xAxis: {
                type: 'category',
                data: dates
            },
            yAxis: [
                {
                    type: 'value',
                    name: '销售额(元)',
                    axisLabel: {
                        formatter: '{value} 元'
                    }
                },
                {
                    type: 'value',
                    name: '订单数',
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            series: [
                {
                    name: '销售额',
                    type: 'line',
                    data: amounts
                },
                {
                    name: '订单数',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: counts
                }
            ]
        });
    })
    .catch(error => console.error('Error loading sales data:', error));

// 加载用户行为数据
fetch('/analytics/api/user_behavior')
    .then(response => response.json())
    .then(data => {
        // 定义行为类型映射
        const behaviorNames = {
            'page_view': '页面浏览',
            'view_box': '查看商品',
            'view_market': '查看超市',
            'view_order': '查看订单',
            'add_to_cart': '加入购物车',
            'form_submit': '表单提交',
            'search': '搜索',
            'test': '测试',
            'browse': '浏览',
            'view': '查看',
            'add_cart': '加入购物车',
            'purchase': '购买'
        };
        
        behaviorChart.setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: data.map(item => {
                    const actionType = item.behavior_type || item.action_type;
                    return behaviorNames[actionType] || actionType;
                })
            },
            series: [
                {
                    name: '用户行为',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: data.map(item => {
                        const actionType = item.behavior_type || item.action_type;
                        const name = behaviorNames[actionType] || actionType;
                        return {name, value: item.count};
                    })
                }
            ]
        });
    })
    .catch(error => console.error('Error loading behavior data:', error));

// 加载热门盲盒数据
fetch('/analytics/api/popular_boxes')
    .then(response => response.json())
    .then(data => {
        const tableBody = document.getElementById('popular-boxes');
        tableBody.innerHTML = '';
        
        data.forEach((box, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${index + 1}</td>
                <td>
                    <img src="${box.image_url}" alt="${box.name}" width="40" class="me-2">
                    <a href="/blind_box/detail/${box.box_id}">${box.name}</a>
                </td>
                <td>¥${box.revenue.toFixed(2)}</td>
                <td>${box.order_count}</td>
            `;
            tableBody.appendChild(row);
        });
    })
    .catch(error => console.error('Error loading popular boxes:', error));

// 图表响应式调整
window.addEventListener('resize', () => {
    salesChart.resize();
    behaviorChart.resize();
});
</script>
{% endblock %}
